<?php
/**
 * licenses : MIT
 * creatTime: 2020/5/13
 * author : weblinuxgame
 * filename: UserLogin.php
 */

namespace App\Repositories;

use App\Api\Responses\Login\Success;
use App\Core\Utils\Message;
use App\Core\Utils\Result;
use App\Core\Interfaces\ResultInterface;
use App\Services\UserApiTokenService;
use App\Services\UserService;

/**
 * Class UserLogin
 * @package App\Repositories
 */
class UserLoginRepository
{
    /**
     * 用户登陆逻辑
     * @param string $username
     * @param string $password
     * @return ResultInterface
     */
    public function login(string $username, string $password): ResultInterface
    {
        $user = UserService::getInstance()->getByKey('username', $username);
        if (empty($user)) {
            return Result::fail(Message::message(Message::UserNotExists), Message::UserNotExists);
        }
        if (!UserService::verifyPassword($user->password, $password)) {
            return Result::fail(Message::message(Message::PasswordNotMatch), Message::PasswordNotMatch);
        }
        $token = UserApiTokenService::getInstance()->store($user)->toString();
        $info = new Success($user, $token);
        return Result::success($info->data, $info->message);
    }

    /**
     * 退出登陆
     * @param string $token
     * @return ResultInterface
     */
    public function logout(string $token): ResultInterface
    {
        if (UserApiTokenService::getInstance()->delete($token)) {
            return Result::success(null, '注销登陆成功');
        }
        return Result::fail('注销登陆失败');
    }

}
